package edu.gatech.TNE.wonderLab7000.validation;

import java.sql.*;

import edu.gatech.TNE.wonderLab7000.person.person;
import edu.gatech.TNE.wonderLab7000.util.WonderLogger;
import oracle.jdbc.pool.OracleDataSource;

public class validation {
	private person personOut;
	private String query;
    private Connection conn;
    private ResultSet result;
    private int access, active;
    public WonderLogger logger = new WonderLogger("mine");
	
    public static void main(String[] args) throws SQLException
    {
    	validation validate = new validation();
    	System.out.println(validate.validator("labAdmin", "password"));
    }
    
    /**
     * Connect to Matt's Oracle database held on the acme.gatech.edu Server
     * @throws SQLException
     */
	public void connect() throws SQLException {
        OracleDataSource ods = new OracleDataSource();
        ods.setURL("jdbc:oracle:thin:ops$mdye3/wonderLab@acme.gatech.edu:1525:public"); 
        conn = ods.getConnection();
    }
	/**
	 * Will check the user name and password against the users in the system
	 * @param username
	 * @param password
	 * @return An int based upon the users access level. Will return 0 if there is a mismatch or user is not found.
	 * @throws SQLException
	 */
	public person validator (String username, String password) throws SQLException {
		
		connect();
		query = "SELECT * FROM USERS WHERE USERID ='" + username + "'";
    	PreparedStatement statement = conn.prepareStatement(query);
    	
        try {
			result = statement.executeQuery();
		} catch (SQLException e) {
			System.out.println(e.toString());
		} 
		
		if (result.next()) {
			
			query = "SELECT * FROM USERS WHERE USERID ='" + username + "' AND PASSWORD ='" + password + "'";
			statement = conn.prepareStatement(query);
		
			try {
				result = statement.executeQuery();
			} catch (SQLException e) {
				System.out.println(e.toString());
			} 
			
			if (result.next()) {
	            access = result.getInt("ACCESSLEVEL");
	            active = result.getInt("ACTIVE");
	            conn.close();
	            statement.close();
	            result.close();
	            if (active == 1) { //Return the access level if active.
	            	personOut = new person(username, access);
		            return personOut;     	
	            }
	            else {	
	            	return new person(username, 0);
	            }
	        }
			else {
	            conn.close();
	            statement.close();
	            result.close();
	            logger.error("Failed login attempt");
	            return new person(username, 0);
			}

        }
		else {
        	conn.close();
            statement.close();
            result.close();
            logger.error("Failed login attempt");
			return new person(username, 0);
		}
    }
}